package qeug.shsh.task;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import kd.bos.context.RequestContext;
import kd.bos.dataentity.OperateOption;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.metadata.dynamicobject.DynamicObjectType;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.exception.KDException;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.orm.ORM;
import kd.bos.orm.query.QFilter;
import kd.bos.schedule.executor.AbstractTask;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.taxc.common.util.StringUtil;
import org.springframework.util.Base64Utils;
import qeug.shsh.helper.FacadeHelper;

import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;

public class PersonTaskPulgin extends AbstractTask {
    /**
     * 人员、收款信息、员工供应商
     */
    private static final Log logs = LogFactory.getLog(SupplierToMDMTaskPlugin.class);

    @Override
    public void execute(RequestContext requestContext, Map<String, Object> map) throws KDException {
//    public void beforeItemClick(BeforeItemClickEvent evt) {//
//        String operationKey = evt.getOperationKey();
//        if ("donothing".equals(operationKey)) {//
        try {
            SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
            JSONObject body = new JSONObject();
            body.put("STARTTIME", df.format(new Date()));
            body.put("ENDTIME", new Date(System.currentTimeMillis() - 1000 * 60 * 60 * 24));
            String basicAuthUserName = System.getProperty("hr.user");
            String basicAuthPassword = System.getProperty("hr.password");
            String basic = basicAuthUserName + ":" + basicAuthPassword;
            String encde = Base64Utils.encodeToString(basic.getBytes(StandardCharsets.UTF_8));
            String hrUrl = System.getProperty("hr.url");
            String json = HttpRequest.post(hrUrl)
                    .header("Authorization", "Basic " + encde)
                    .body(body.toString())
                    .execute().body();
//                String json = "{\n" +
//                        "    \"PERSONINFO\": [\n" +
//                        "        {\n" +
//                        "            \"NUMBER\": \"0002\",\n" +
//                        "            \"NAME\": \"徐海辉人员测试2\",\n" +
//                        "            \"STATUS\": \"1\",\n" +
//                        "            \"GRADE\": \"6\",\n" +
//                        "            \"GRADENAME\": \"职级名称\",\n" +
//                        "            \"PHONE\": \"15970264111\",\n" +
//                        "            \"GENDER\": \"1\",\n" +
//                        "            \"IDCARD\": \"341024199010248917\",\n" +
//                        "            \"COSTNUMBER\": \"001\",\n" +
//                        "            \"COSTNAME\": \"行政组织\",\n" +
//                        "            \"BANKS\": [\n" +
//                        "                {\n" +
//                        "                    \"PAYERACCOUNT\": \"1587111111\",\n" +
//                        "                    \"PAYERACCOUNTNAME\": \"测试2\",\n" +
//                        "                    \"PAYERBANK\": \"105307000112\",\n" +
//                        "                    \"PAYERBANKNAME\": \"中国建设银行股份有限公司连云港港口支行\"\n" +
//                        "                }\n" +
//                        "            ],\n" +
//                        "            \"COSTENTRY\": [\n" +
//                        "                {\n" +
//                        "                    \"ISINCHARGE\": true,\n" +
//                        "                    \"ISPARTJOB\": true,\n" +
//                        "                    \"POSITION\": \"开发\",\n" +
//                        "                    \"DPT_NUMBER\": \"5300\"\n" +
//                        "                }\n" +
//                        "            ]\n" +
//                        "        }\n" +
//                        "    ]\n" +
//                        "}";//
            JSONArray jsonArray = JSONObject.parseObject(json).getJSONArray("PERSONINFO");
            for (int i = 0; i < jsonArray.size(); i++) {
                //记录接口日志
                HashMap<String, Object> log = new HashMap<>();
                log.put("operationModule", "HR人员接口");
                log.put("url", hrUrl);
                log.put("user", basicAuthUserName);
                log.put("mode", "POST");
                log.put("action", "");
                log.put("opdate", new Date());
                log.put("mainstring", json);

                StringBuffer stringBuffer = new StringBuffer();
                JSONObject data = jsonArray.getJSONObject(i);
                String number = data.getString("NUMBER");//编码
                String name = data.getString("NAME");//姓名
                String status = data.getString("STATUS");//状态
                String GRADE = data.getString("GRADE");//职级码
                String GRADENAME = data.getString("GRADENAME");//职等名称
                String phone = data.getString("PHONE");//手机
                String gender = data.getString("GENDER");//性别
                String idCard = data.getString("IDCARD");//身份证
/*                    String costNumber = data.getString("COSTNUMBER");//成本中心编码
                    String costName = data.getString("COSTNAME");//成本中心名称*/
//                Date birthday = data.getDate("birthday");//生日
//                String email = data.getString("email");//邮箱
//                String username = data.getString("username");//用户名
//                String fullpinyin = data.getString("fullpinyin");//姓名全拼
//                String simplepinyin = data.getString("simplepinyin");//姓名简拼
                JSONArray banks = data.getJSONArray("BANKS");//银行分录
                JSONArray costEntry = data.getJSONArray("COSTENTRY");//部门分录
                if (!StringUtil.isNotEmpty(number)) {
                    stringBuffer.append("员工编码不能为空！");
                }
                if (!StringUtil.isNotEmpty(name)) {
                    stringBuffer.append("员工姓名不能为空！");
                }
                if (!StringUtil.isNotEmpty(status)) {
                    stringBuffer.append("状态不能为空！");
                }
                if (!StringUtil.isNotEmpty(phone)) {
                    stringBuffer.append("员工手机号不能为空！");
                }
//                  if (!StringUtil.isNotEmpty(grade)) {
//                    stringBuffer.append("员工职等不能为空！");
//                  }
                if (banks == null) {
                    stringBuffer.append("银行分录不能为空！");
                }
                if (costEntry == null) {
                    stringBuffer.append("部门分录不能为空！");
                }
/*                    if (costNumber == null || costName == null) {
                        stringBuffer.append("成本中心编码或名称不能为空！");
                    }*/
                if (stringBuffer.length() > 0) {
                    log.put("responsebody", stringBuffer);
                    log.put("pdesc", "失败");
                    FacadeHelper.apiLog(log);
                    continue;
                }
                ORM orm = ORM.create();
                DynamicObject person = orm.newDynamicObject("bos_user");
                DynamicObject user = BusinessDataServiceHelper.
                        loadSingle("bos_user", new QFilter("number", "=", number).toArray());
                if (user != null) {//判断人员是否存在
                    person = user;
                }
                person.set("number", number);
                person.set("name", name);
                if ("2".equals(status)) {
                    person.set("enable", "0");
                    person.set("status", "A");
                } else {
                    person.set("enable", "1");
                    person.set("status", "C");
                }
                person.set("phone", phone);
                person.set("idcard", idCard);
                person.set("gender", gender);
                person.set("username", number);
//                person.set("birthday", birthday);
//                person.set("email", email);
//                person.set("fullpinyin", fullpinyin);
//                person.set("simplepinyin", simplepinyin);
//                person.set("enable", "1");

                //获取单据体集合
                DynamicObjectCollection bankCollection = person.getDynamicObjectCollection("qeug_bankentry");//银行信息分录
                //根据Type创建单据体对象
                DynamicObjectType bankType = bankCollection.getDynamicObjectType();
                bankCollection.clear();
                for (int x = 0; x < banks.size(); x++) {
                    JSONObject bank = banks.getJSONObject(x);
                    //根据Type创建单据体对象
                    DynamicObject banksEntry = new DynamicObject(bankType);
                    String payerAccount = bank.getString("PAYERACCOUNT");//银行账号
                    String payerAccountName = bank.getString("PAYERACCOUNTNAME");//账户名称（收款人）
                    String payerBank = bank.getString("PAYERBANK");//银行代码
                    DynamicObject bd_bebank = BusinessDataServiceHelper.
                            loadSingle("bd_bebank", new QFilter("number", "=", payerBank).toArray());
                    banksEntry.set("qeug_payeraccount", payerAccount);
                    banksEntry.set("qeug_payeraccountname", payerAccountName);
                    banksEntry.set("qeug_payerbank", bd_bebank);
                    //添加到单据体集合
                    bankCollection.add(banksEntry);
                }

                DynamicObjectCollection costCollection = person.getDynamicObjectCollection("entryentity"); //部门信息分录
                DynamicObjectType entryType = costCollection.getDynamicObjectType();
                costCollection.clear();
                for (int x = 0; x < costEntry.size(); x++) {
                    JSONObject entry = costEntry.getJSONObject(x);
                    DynamicObject cost = new DynamicObject(entryType);
//                        Entry.set("isincharge", entry.getString(""));
//                        Entry.set("ispartjob", entry.getString(""));
                    DynamicObject dptInfo = BusinessDataServiceHelper.
                            loadSingle("bos_adminorg", new QFilter("number", "=", entry.getString("DPT_NUMBER")).toArray());
                    cost.set("position", entry.getString("POSITION"));//职位
                    cost.set("dpt", dptInfo);//部门编码
                    costCollection.add(cost);
                }
//                    if (user == null) {
//                        //用户不存在，新增用户
//                        audit = SaveServiceHelper.saveOperate("bos_user", new DynamicObject[]{person}, option);//新增
//                        System.out.println();
//                    } else {
                //用户存在，修改用户
//                      SaveServiceHelper.update(person);//修改
//                      String opStr="save";//提交submit、审核audit,删除delete
                OperationResult audit = SaveServiceHelper.saveOperate("bos_user", new DynamicObject[]{person}, OperateOption.create());//新增、修改
                System.out.println();

                if (audit.isSuccess()) {
                    //人员新增修改成功记录成功日志
                    log.put("responsebody", audit);
                    log.put("pdesc", "成功");
                    FacadeHelper.apiLog(log);

/*                        //人员新增修改成功在成本中心人员字段中添加人员
                        QFilter f1 = new QFilter("number", "=", costNumber);
                        QFilter f2 = new QFilter("name", "=", costName);
                        QFilter[] f = new QFilter[]{f1, f2};
                        //通过编码查询成本中心
                        DynamicObject cost = BusinessDataServiceHelper.loadSingle("bos_costcenter",f);
                        //获取成本中心人员集合
                        DynamicObjectCollection costUserCollection = cost.getDynamicObjectCollection("qeug_costuser");
                        String personNumber = person.getString("number");//人员编码
                        int a = 0;
                        for (DynamicObject costUser : costUserCollection) {
                            DynamicObject costUsers = (DynamicObject) costUser.get(1);
                            String costUserNumber = costUsers.getString("number");//成本中心人员编码
                            if (costUserNumber.equals(personNumber)) {
                                //成本中心人员已存在
                                a++;
                            }
                        }
                        if (a == 0){
                            //成本中心人员不存在添加人员
                            DynamicObject costUserType = new DynamicObject(costUserCollection.getDynamicObjectType());
                            costUserType.set("fbasedataId",person);
                            costUserCollection.add(costUserType);
                            cost.set("qeug_costuser",costUserCollection);
                        }
                        OperationResult ces = SaveServiceHelper.saveOperate("bos_costcenter", new DynamicObject[]{cost}, OperateOption.create());//修改
                        System.out.println();*/

                    //人员新增或修改完成注册人员供应商
//                    DynamicObject supplier = orm.newDynamicObject("bd_supplier");
//                    DynamicObject supUser = BusinessDataServiceHelper.loadSingle("bos_user", "id", new QFilter("number", "=", number).toArray());
//                    DynamicObject supp = BusinessDataServiceHelper.loadSingle("bd_supplier", new QFilter("employee.id", "=", supUser.get("id")).toArray());
//                    if (supp != null) {
//                        supplier = supp;
//                    }
//                    supplier.set("number", number);//编码
//                    supplier.set("name", name);//名称
//                    supplier.set("bizpartner_phone", phone);//电话
////                        supplier.set("postal_code", email);//电子邮箱
//                    supplier.set("idno", idCard);//身份证
//                    supplier.set("type", "4");//伙伴类型
//                    supplier.set("ctrlstrategy", "2");//控制策略“默认自由分配”
//                    DynamicObject createOrgName = BusinessDataServiceHelper.loadSingle("bos_adminorg", new QFilter("name", "=", "盛虹集团").toArray());
//                    supplier.set("createorg", createOrgName);//创建组织默认盛虹石化
//                    DynamicObject supPer = BusinessDataServiceHelper.loadSingle("bos_user", new QFilter("number", "=", number).toArray());
//                    supplier.set("employee", supPer);//员工
//                    if ("2".equals(status)) {
//                        supplier.set("enable", "0");
//                        supplier.set("status", "A");
//                    } else {
//                        supplier.set("enable", "1");
//                        supplier.set("status", "C");
//                    }
//                    DynamicObjectCollection banksCollection = supplier.getDynamicObjectCollection("entry_bank");//银行分录
//                    DynamicObject currencyNumber = BusinessDataServiceHelper.loadSingle("bd_currency", new QFilter("number", "=", "CNY").toArray());
//                    DynamicObjectType supBankType = banksCollection.getDynamicObjectType();
//                    banksCollection.clear();
//                    for (int k = 0; k < banks.size(); k++) {
//                        JSONObject bank = banks.getJSONObject(k);
//                        DynamicObject banksEntry = new DynamicObject(supBankType);
//                        //同一个银行账号 不能同时存在在不同编码的客商内
//                        String payerAccount = bank.getString("PAYERACCOUNT");//银行账号
//                        String payerAccountName = bank.getString("PAYERACCOUNTNAME");//账户名称
////                            String payerBank = bank.getString("payerbank");//开户行号
//                        String payerBankNum = bank.getString("PAYERBANK");//开户银行编码
//                        DynamicObject bankName = BusinessDataServiceHelper.loadSingle("bd_bebank", new QFilter("number", "=", payerBankNum).toArray());
//                        banksEntry.set("bankaccount", payerAccount);//银行账号
//                        banksEntry.set("accountname", payerAccountName);//账户名称
//                        banksEntry.set("currency", currencyNumber);//币种代码
//                        banksEntry.set("bank", bankName);//开户银行
//                        boolean isdefault = true;
//                        banksEntry.set("isdefault_bank", isdefault);//默认是否职员
//                        banksCollection.add(banksEntry);
//
//                        //收款信息新增
//                        DynamicObject payeer = orm.newDynamicObject("er_payeer");
//                        DynamicObject pay = BusinessDataServiceHelper.loadSingle("er_payeer", new QFilter("payer.id", "=", supUser.get("id")).toArray());
//                        if (pay != null) {
//                            payeer = pay;
//                        }
//                        payeer.set("isemployee", true);//是否职员
//                        payeer.set("payer", supPer);//收款人
//                        payeer.set("creator", supPer);//创建人
//                        payeer.set("outpayer", supPer.getString("name"));//收款人文本字段
//                        payeer.set("payerbank", bankName);//收款银行
//                        payeer.set("currency", currencyNumber);//币别
//                        payeer.set("payeraccount", null);//银行账号
//                        payeer.set("payeraccount", payerAccount);//银行账号
//                        payeer.set("payeraccountname", payerAccountName);//账户名称
//                        payeer.set("ctrlstrategy", "2");//控制策略“默认自由分配”
//                        payeer.set("createorg", createOrgName);//创建组织默认盛虹石化
//                        if ("2".equals(status)) {
//                            payeer.set("enable", "0");
//                        } else {
//                            payeer.set("enable", "1");
//                        }
//                        //多选基础资料使用人
///*                            DynamicObjectCollection useridCollection = payeer.getDynamicObjectCollection("userid");
//                            DynamicObject useridUserType = new DynamicObject(useridCollection.getDynamicObjectType());
//                            useridUserType.set("fbasedataId",supPer);
//                            useridCollection.add(useridUserType);
//                            payeer.set("userid",useridCollection);//使用人
//                            payeer.set("isshare",true);//授权使用*/
//                        OperationResult er_payeer = SaveServiceHelper.saveOperate("er_payeer", new DynamicObject[]{payeer}, OperateOption.create());//新增
//                        System.out.println();
//                        if (er_payeer.isSuccess()) {
//                            logs.info("收款信息新增修改成功");
//                        } else {
//                            logs.info("收款信息新增修改失败，错误代码：" + er_payeer);
//                        }
//                    }
//                    DynamicObjectCollection entry_groupstandard = supplier.getDynamicObjectCollection("entry_groupstandard");//供应商分类
//                    DynamicObjectType groupstandardType = entry_groupstandard.getDynamicObjectType();
//                    DynamicObject groupstandardEntry = new DynamicObject(groupstandardType);
//                    DynamicObject bd_suppliergroupstandard = BusinessDataServiceHelper.loadSingle("bd_suppliergroupstandard", new QFilter("number", "=", "JBFLBZ").toArray());
//                    groupstandardEntry.set("standardid", bd_suppliergroupstandard);//分类标准
//                    DynamicObject bd_suppliergroup = BusinessDataServiceHelper.loadSingle("bd_suppliergroup", new QFilter("number", "=", "SK98").toArray());
//                    groupstandardEntry.set("groupid", bd_suppliergroup);//分类
//                    entry_groupstandard.add(groupstandardEntry);
//
//                    OperationResult bd_supplier = SaveServiceHelper.saveOperate("bd_supplier", new DynamicObject[]{supplier}, OperateOption.create());//新增修改
//                    System.out.println();
//                    if (bd_supplier.isSuccess()) {
//                        logs.info("人员供应商新增修改成功");
//                    } else {
//                        logs.info("人员供应商新增修改失败，错误代码：" + bd_supplier);
//                    }
//                } else {
//                    log.put("responsebody", audit);
//                    log.put("pdesc", "失败");
//                    FacadeHelper.apiLog(log);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
